﻿package mortal.common.preLoadPage
{
    import Engine.RMI.*;
    import Framework.MQ.*;
    import Framework.Util.*;
    import Message.Command.*;
    import Message.Login.*;
    import Message.Public.*;
    import com.gengine.debug.*;
    import com.gengine.global.*;
    import com.gengine.resource.loader.*;
    import com.gengine.ui.*;
    import extend.language.*;
    import extend.php.*;
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.text.*;
    import flash.utils.*;
    import mortal.common.error.*;
    import mortal.common.global.*;
    import mortal.game.net.rmi.login.*;
    import mortal.mvc.core.*;

    public class PreLoginProxy extends EventDispatcher
    {
        public var rootStage:Stage;
        private var _gameSession:GameSession;
        private var _slogin:SLogin;
        public var sloginReturn:SLoginReturn;
        private var _createRole:MovieClip;
        private var _isIntroduceMovieEnd:Boolean = true;
        public var isLoginSuccess:Boolean = false;
        private var _createRoleLoader:Loader;
        private var _isCreateRoleCompl:Boolean = false;
        private var _reloadTime:int;
        private var urlloader:URLLoader;
        private var baseLoader:DataLoader;
        private var _isLoadedApp:Boolean = false;
        private static var _instance:PreLoginProxy;
        public static const LOGIN_SUCCESS:String = "loginSuccess";
        public static const CreateRoleSuccess:String = "CreateRoleSuccess";
        public static const PlayerIntroduceMovieEnd:String = "PlayerIntroduceMovieEnd";

        public function PreLoginProxy()
        {
            this.urlloader = new URLLoader();
            this.baseLoader = new DataLoader();
            if (_instance)
            {
                throw new Error("单例！");
            }
            ErrorCode.init();
            return;
        }// end function

        public function get isIntroduceMovieEnd() : Boolean
        {
            return this._isIntroduceMovieEnd;
        }// end function

        public function set isIntroduceMovieEnd(param1:Boolean) : void
        {
            this._isIntroduceMovieEnd = param1;
            if (param1)
            {
                dispatchEvent(new Event(PlayerIntroduceMovieEnd));
            }
            return;
        }// end function

        public function login() : void
        {
            this._gameSession = new GameSession();
            this._gameSession.loginSession.url = ParamsConst.instance.loginIP;
            LoginRMI.instance.rmiSession = this._gameSession.loginSession;
            RMIConnection.connetIPPort = ParamsConst.instance.loginIP;
            Log.debug("登陆服务器：" + this._gameSession.loginSession.url);
            this._slogin = new SLogin();
            this._slogin.username = ParamsConst.instance.username;
            this._slogin.userId = ParamsConst.instance.userId;
            this._slogin.server = ParamsConst.instance.server;
            this._slogin.time = ParamsConst.instance.time as Date;
            this._slogin.flag = ParamsConst.instance.flag;
            this._slogin.country = ParamsConst.instance.defaultCamp;
            this._slogin.isAdult = ParamsConst.instance.isAdult;
            this._slogin.codeVersion = ParamsConst.Version;
            this._slogin.platformCode = ParamsConst.instance.platformCode;
            this._slogin.password = ParamsConst.instance.password;
            this._slogin.loginIp = ParamsConst.instance.loginIP;
            this._slogin.totalOnlineTime = ParamsConst.instance.totalOnlineTime;
            this._slogin.platformUserName = ParamsConst.instance.platformUserName;
            this._slogin.issm = ParamsConst.instance.issm;
            this._slogin.gateIp = ParamsConst.instance.gameIP;
            NetDispatcher.addCmdListener(EPublicCommand._ECmdPublicLoginInfoShow, this.onShowLoginInfo);
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.Login);
            }
            LoginRMI.instance.loginProxy.login_async(new AMI_ILogin_login(this.loginSuccess, this.loginException), this._slogin);
            return;
        }// end function

        public function loginSuccess(param1:Object, param2:SLoginReturn, param3:Array = null) : void
        {
            if (param3 && param3.length > 0)
            {
                PreloaderCache.isMultipleRole = true;
                PreloaderCache.myRoles = param3;
                dispatchEvent(new Event(LOGIN_SUCCESS));
                this.initApp();
            }
            else
            {
                if (this._gameSession.loginSession && this._gameSession.loginSession.session)
                {
                    this._gameSession.loginSession.session.abandon();
                }
                this._gameSession.gmaeSession.url = SUrl(param2.urls[0]).url;
                Log.debug("登陆游戏服务器：" + this._gameSession.gmaeSession.url);
                this.sloginReturn = param2;
                this.removeCreateRole();
                if (GameLoadBar.instance && !GameLoadBar.instance.visible)
                {
                    GameLoadBar.instance.visible = true;
                }
                PHPSender.renrenAttention();
                this.isLoginSuccess = true;
                if (!PreloaderCache.isMultipleRole)
                {
                    this.initApp();
                }
                if (PHPSender.isCreateRole)
                {
                    PHPSender.sendToURLByPHP(SenderType.CreateRoleSuccess);
                    dispatchEvent(new Event(CreateRoleSuccess));
                }
                dispatchEvent(new Event(LOGIN_SUCCESS));
            }
            return;
        }// end function

        public function createRoleException(param1:Exception) : void
        {
            var _loc_2:* = ErrorCode.getErrorByLogin(param1.code);
            if (this._createRole && this._createRole.parent)
            {
                this._createRole.showException(_loc_2, param1.code);
            }
            else if (!this.isLoginSuccess)
            {
                this.showErrorInfo(param1);
            }
            PHPSender.sendToURLByPHP(SenderType.CreateRoleFail, param1.message);
            return;
        }// end function

        public function loginException(param1:Exception) : void
        {
            if (param1.code == ErrorCode.ErrorLogin_NoRole)
            {
                PHPSender.isCreateRole = true;
                this.createRole();
            }
            else
            {
                if (!this.isLoginSuccess)
                {
                    this.showErrorInfo(param1);
                }
                PHPSender.sendToURLByPHP(SenderType.LoginFail, "错误码：" + param1.code + "\n错误信息：" + param1.message);
            }
            return;
        }// end function

        public function createRole() : void
        {
            this._createRoleLoader = new Loader();
            this._createRoleLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onLoadRoleHandler, false, 0, true);
            this._createRoleLoader.load(new URLRequest(PathConst.createRoleUrl));
            PHPSender.sendToURLByPHP(SenderType.LoadCreateRole);
            return;
        }// end function

        private function onRoleCompleteHandler(event:Event) : void
        {
            this._isCreateRoleCompl = true;
            this.clearReloadTime();
            if (GameLoadBar.instance && GameLoadBar.instance.visible)
            {
                GameLoadBar.instance.visible = false;
            }
            var _loc_2:* = event.target as LoaderInfo;
            _loc_2.removeEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
            _loc_2.removeEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
            _loc_2.removeEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
            this._createRole = _loc_2.content as MovieClip;
            this._createRole.mainPath = ParamsConst.instance.mainPath;
            this._createRole.version = ParamsConst.Version;
            this._createRole.randomNameUrl = ParamsConst.instance.randomNameUrl;
            if (this._createRole.hasOwnProperty("isAutoEnterGame"))
            {
                this._createRole.isAutoEnterGame = ParamsConst.instance.isAutoEnterGame;
            }
            this.rootStage.addChild(this._createRole);
            this._createRole.setDefaultParams(ParamsConst.instance.roleName, ParamsConst.instance.defaultSex, ECamp._ECampA);
            this._createRole.submitFun = this.submitFun;
            if (this._createRole.hasOwnProperty("whoPlayGame"))
            {
                this._createRole.whoPlayGame(ParamsConst.instance.friendPlayGameUrl, ParamsConst.instance.whoPlayGameUrl);
            }
            this.rootStage.addEventListener(MouseEvent.CLICK, this.onCreateRoleClickHandler);
            PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleSuccess);
            this.initApp();
            return;
        }// end function

        private function onLoadRoleHandler(event:ErrorEvent) : void
        {
            PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleFail, event.text);
            return;
        }// end function

        private function onCreateRoleClickHandler(event:MouseEvent) : void
        {
            PHPSender.sendToURLByPHP(SenderType.ClickCreateRole);
            this.rootStage.removeEventListener(MouseEvent.CLICK, this.onCreateRoleClickHandler);
            return;
        }// end function

        public function onShowLoginInfo(param1:MessageBlock) : void
        {
            var _loc_2:* = param1.messageBase as SLoginInfoShow;
            if (this._createRole && this._createRole.parent)
            {
                Object(this._createRole).addShowInfo(_loc_2.camp, _loc_2.sex, _loc_2.name);
            }
            return;
        }// end function

        private function removeCreateRole() : void
        {
            if (this._createRole && this._createRole.parent)
            {
                this._createRole.stop();
                this._createRole.parent.removeChild(this._createRole);
                this._createRole = null;
                this._createRoleLoader.unloadAndStop();
                this._createRoleLoader = null;
            }
            return;
        }// end function

        private function onRoleProgressHandler(event:ProgressEvent) : void
        {
            GameLoadBar.instance.setProgress(PreloaderConfig.LOAD_CREATE_ROLE, event.bytesLoaded, event.bytesTotal);
            if (event.bytesLoaded == event.bytesTotal && !this._isCreateRoleCompl)
            {
                this.clearReloadTime();
                this._reloadTime = setTimeout(this.reloadCreateRole, 2000);
            }
            return;
        }// end function

        private function clearReloadTime() : void
        {
            if (this._reloadTime)
            {
                clearTimeout(this._reloadTime);
                this._reloadTime = 0;
            }
            return;
        }// end function

        private function reloadCreateRole() : void
        {
            this.clearReloadTime();
            this._createRoleLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
            this._createRoleLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
            this._createRoleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
            this._createRoleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onLoadRoleHandler, false);
            this._createRoleLoader.unload();
            var _loc_1:* = PathConst.createRoleUrl;
            var _loc_2:* = _loc_1.indexOf("?");
            if (_loc_2 >= 0)
            {
                _loc_1 = _loc_1 + Math.random();
            }
            else
            {
                _loc_1 = _loc_1 + ("?v=" + Math.random());
            }
            this._createRoleLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
            this._createRoleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onLoadRoleHandler, false, 0, true);
            this._createRoleLoader.load(new URLRequest(_loc_1));
            return;
        }// end function

        private function submitFun(param1:Object) : void
        {
            this.sendCreateRole(param1);
            return;
        }// end function

        private function sendCreateRole(param1:Object) : void
        {
            var _loc_2:* = new SFirstRole();
            _loc_2.career = ECareer._ECareerNo;
            _loc_2.sex = param1.sex;
            _loc_2.name = param1.name;
            _loc_2.camp = ECamp._ECampA;
            _loc_2.career = param1.career;
            _loc_2.server = ParamsConst.instance.server;
            _loc_2.platformCode = ParamsConst.instance.platformCode;
            LoginRMI.instance.loginProxy.createFirstRole_async(new AMI_ILogin_createFirstRole(this.loginSuccess, this.createRoleException), _loc_2);
            return;
        }// end function

        public function get gameSession() : GameSession
        {
            return this._gameSession;
        }// end function

        public function set gameSession(param1:GameSession) : void
        {
            this._gameSession = param1;
            return;
        }// end function

        public function get slogin() : SLogin
        {
            return this._slogin;
        }// end function

        public function set slogin(param1:SLogin) : void
        {
            this._slogin = param1;
            return;
        }// end function

        private function initApp() : void
        {
            if (this._isLoadedApp == false)
            {
                this._isLoadedApp = true;
                this.baseLoader.maxReloadTimes = 30;
                this.baseLoader.reloadSec = 8;
                this.baseLoader.addEventListener(Event.COMPLETE, this.onCompleteHandler);
                this.baseLoader.addEventListener(ProgressEvent.PROGRESS, this.onProgressHandler);
                this.baseLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onIOErrorHandler);
                this.baseLoader.load(PathConst.gameUrl + "?v=" + ParamsConst.instance.flashVersion, null);
            }
            return;
        }// end function

        private function onCompleteHandler(event:Event) : void
        {
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadMaigGameSwfSuccess);
            }
            var _loc_2:* = new Loader();
            _loc_2.loadBytes(event.target.bytesData as ByteArray);
            _loc_2.mouseEnabled = false;
            _loc_2.contentLoaderInfo.addEventListener(Event.INIT, this.initMainGame);
            return;
        }// end function

        private function initMainGame(event:Event) : void
        {
            var _loc_2:* = LoaderInfo(event.currentTarget).content as Application;
            _loc_2.initMainThread(this.rootStage);
            return;
        }// end function

        private function onProgressHandler(event:ProgressEvent) : void
        {
            GameLoadBar.instance.setProgress(PreloaderConfig.LOAD_MAIN_GAME, event.bytesLoaded, event.bytesTotal);
            return;
        }// end function

        private function onIOErrorHandler(event:ErrorEvent) : void
        {
            if (PHPSender.isCreateRole)
            {
                PHPSender.sendToURLByPHP(SenderType.LoadMaigGameSwfFail, event.text);
            }
            return;
        }// end function

        private function showErrorInfo(param1:Exception) : void
        {
            var _loc_2:* = new TextField();
            _loc_2.autoSize = TextFieldAutoSize.LEFT;
            _loc_2.textColor = 16777215;
            _loc_2.background = true;
            _loc_2.backgroundColor = 0;
            _loc_2.x = this.rootStage.stageWidth / 2 - 100;
            _loc_2.y = this.rootStage.stageHeight / 2 - 40;
            if (Global.isDebugModle)
            {
                _loc_2.text = PreLanguage.getString(154) + param1.code + PreLanguage.getString(155) + param1.message;
                this.rootStage.addChild(_loc_2);
            }
            else
            {
                _loc_2.text = PreLanguage.getString(154) + param1.code + PreLanguage.getString(156);
                this.rootStage.addChild(_loc_2);
            }
            return;
        }// end function

        public function doEnterGame(param1:SMyRole) : void
        {
            this._slogin.playerId = param1.playerId;
            LoginRMI.instance.loginProxy.login_async(new AMI_ILogin_login(this.loginSuccess, this.loginException), this._slogin);
            return;
        }// end function

        public function doSetMain(param1:SMyRole) : void
        {
            this._slogin.playerId = param1.playerId;
            this._slogin.setIsMain = 1;
            LoginRMI.instance.loginProxy.login_async(new AMI_ILogin_login(this.loginSuccess, this.loginException), this._slogin);
            return;
        }// end function

        public static function get instance() : PreLoginProxy
        {
            if (!_instance)
            {
                _instance = new PreLoginProxy;
            }
            return _instance;
        }// end function

    }
}
